package myclassloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义类加载器
 */


public class SimpleAppClassLoaderDemo extends ClassLoader{

    private String basicPath;
    public SimpleAppClassLoaderDemo(String basicPath) {
        this.basicPath = basicPath;
    }

    /**
     * 打破双亲委派模式 
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        try {
            //优先使用,打破双亲委派模式
            return findClass(name);
        } catch (Exception e) {
            //出现异常时,使用默认的类加载器加载
            return super.loadClass(name);
        }
//
    }

    /**
     * 查找类,并读取到内存,然后创建字节码对象
     * @param name 这个类名为全限定名
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classFilePath=basicPath+name.replace(".","\\")+".class";
        File file = new File(classFilePath);
        if (!file.exists()) {
            throw new ClassNotFoundException("没有找到对应的类!");
        }
        FileInputStream fis=null;
        try {
            //读取数据
            fis=new FileInputStream(file);
            byte[] buf=new byte[fis.available()];//.available()读到的字节数
            fis.read(buf);
            //创建字节码对象
            return defineClass(name,buf,0,buf.length);//此方法一般不用重写
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
